#!/usr/bin/python
# -*- coding: utf-8 -*-

import Ice, MySQLdb
import sys, os, datetime, thread

SLICE = os.path.join('..', 'slice')
FILE = os.path.join(SLICE, 'Oculus.ice')
Ice.loadSlice('--all -I/usr/share/slice', ['-I' + SLICE, FILE])

import Oculus

class SnifferI (Oculus.Sniffer):

    def __init__ (self, host, user, passwd, db):

        self.__mutex = thread.allocate_lock()

        try:
            self.__conn = MySQLdb.connect (host, user, passwd, db)
        except MySQLdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
            sys.exit(1)
            
        self.__cursor = self.__conn.cursor ()

    def notify (self, camera, frame, field, value, curr = None):

        self.__mutex.acquire()

        aux = field.split('_')

        # Event or notification.
        if aux[len(aux) - 1] != 'time':
            time = str(datetime.datetime.today())
            if field == 'client_notification':
                self.__cursor.execute ("""INSERT INTO Times (camera, frame,""" + field + """) VALUES (%s, %s, %s)""", (camera, frame, time))
            else:
                self.__cursor.execute ("""UPDATE Times SET """ + field + """=%s WHERE camera=%s AND frame=%s""", (time, camera, frame))

        # Processing time.
        else:
            self.__cursor.execute ("""UPDATE Times SET """ + field + """=%s WHERE camera=%s AND frame=%s""", (value, camera, frame))

        # self.__conn.commit()

        self.__mutex.release()
